<?php

namespace App\Http\Controllers;

use App\Kids\Caches\Branchs;
use App\Models\Admin;
use App\Models\BaseModel;
use App\Models\Notice;
use App\Utils\DataFormatter;
use App\Utils\ModelUtils;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use p5\objects\PropertyUtils;
use p5\objects\SqlMaker;
use p5\objects\TimeUtils;

class BaseController extends Controller
{
    /**
     * @var Request
     */
    protected $request;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }


    public function gridQuery($sql, $ds = null)
    {
        if (empty($ds)) {
            return DB::select($sql);
        }
        return DB::connection($ds)->select($sql);
    }

    public function getQueryLimits()
    {
        return SqlMaker::make_limits($this->request->all());
    }

    public function getOrderBy($defaults = [])
    {
        if (empty($defaults)) {
            return "";
        }
        $string = " order by ";
        $index = 0;
        foreach ($defaults as $key => $value) {
            $string .= $index == 0 ? "" : ",";
            $string .= $key . " " . $value;
            $index++;
        }
        return $string;
    }

    /**
     * @param $model BaseModel
     */
    public function markOrganizationInfo($model)
    {

        $cid = $this->currentOrganizationId();
        $matrix = ["organization_id" => $cid];
        $model->forceFill($matrix);
    }

    /**
     * @param $model BaseModel
     */
    public function markCreateInfo($model)
    {
        $matrix = [
            "created_id" => $this->currentAdminId()
            , "created_by" => $this->currentAdminName()
            , "created_at" => TimeUtils::current_datetime()
        ];
        $model->setBlankAttributes($matrix);
        $this->markUpdateInfo($model);
    }

    /**
     * @param $model BaseModel
     */
    public function markUpdateInfo($model)
    {
        $matrix = ["updated_id" => $this->currentAdminId(), "updated_by" => $this->currentAdminName()];
        $matrix["updated_at"] = TimeUtils::current_datetime();
        $model->setBlankAttributes($matrix);
    }

    public function currentAdminName()
    {
        $name = $this->get("login_user_name");
        if (!empty($name)) {
            return $name;
        }
        $admin = $this->currentAdmin();
        if (empty($admin)) {
            return null;
        }
        return $admin->get_user_name();
    }

    /**
     * @return Admin
     */
    public function currentAdmin()
    {
        $adminId = $this->currentAdminId();
        if ($adminId > 0) {
            // return AdminCacher::findAdminObject($adminId);
        }
        return null;
    }

    public function getIp()
    {
        return $this->request->getClientIp();
    }

    public function currentOpenId()
    {
        return $this->get("openId", 0);
    }

    public function currentAdminId()
    {
        return $this->get("login_admin_id", 0);
    }

    public function currentOrganizationId()
    {
        return $this->get("login_organization_id");
    }


    public function first($names, $defaultValue = "")
    {
        foreach ($names as $name) {
            $v = $this->get($name);
            if (!empty($v)) {
                return $v;
            }
        }
        return $defaultValue;
    }

    public function get($name, $defaultValue = "")
    {
        return $this->request->get($name, $defaultValue);
    }

    public function getArray($name)
    {
        $string = $this->request->get($name, "");
        if ($string === "") {
            return [];
        }
        return explode(",", $string . "");
    }

    public function debug($object)
    {
        Log::debug($object);
    }

    public function warn($object)
    {
        Log::warn($object);
    }

    public function error($object)
    {
        Log::error($object);
    }

    public function toKindTimes(&$list, $propertyNames = [], $withMinute = true)
    {
        DataFormatter::toKindTimes($list, $propertyNames, $withMinute);
    }

    protected function loadFiles()
    {
        // $acceptFileTypes = ["jpg", "jpeg", "png", "gif"];
        // phpinfo();
        $files = [];
        // var_dump($_FILES);
        if (isset($_FILES) && !empty($_FILES)) {
            foreach ($_FILES as $key => $file) {
                $filename = $file["name"];
                $fileError = $file["error"][0];

                if ($fileError != 0) {
                    // 1= '上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值';
                    // 2= '上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值';
                    // 3= '文件只有部分被上传';
                    // 4= '没有文件被上传';
                    // 6= '找不到临时文件夹';
                    // 7= '文件写入失败（磁盘空间满）';
                    throw new \Exception("error code: " . $fileError, "upload.exception");
                }
                if (strpos(".php", $filename) !== false) {
                    Log::warn("拦截到一份高危的上传文档:" . json_decode($file));
                    throw new \Exception("文件名中不能含有 .php ", "php.file.not.allow");
                }
                //            $type = strtolower(filetype($filename));
                //            if (!in_array($acceptFileTypes)) {
                //                $this->throwException("file.type.not.allow", "类型为 $type 的文件不被接收,允许类型:" + json_decode($acceptFileTypes));
                //            }
                // save file
                $files[count($files)] = $file;
            }
        }
        return $files;
    }

}
